<template>
    <div class="language-switcher">
        <button 
            v-for="localeItem in supportedLocales" 
            :key="localeItem"
            :class="{ active: currentLocale === localeItem }"
            @click="changeLanguage(localeItem)"
        >
            {{ $t(`language.${localeItem}`) }}
        </button>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import i18n, { loadLanguageAsync, supportedLocales } from '../i18n';

const { locale } = useI18n();

const currentLocale = ref(locale.value)

const changeLanguage = async (newLocale: string) => {
    if (currentLocale.value === newLocale) return; // 如果是当前语言则不处理
    
    try {
        await loadLanguageAsync(newLocale);
        locale.value = newLocale;
        currentLocale.value = newLocale;
        localStorage.setItem('user-language', newLocale);
        document.documentElement.lang = newLocale;
    } catch (error) {
        console.error(`Failed to change language to: ${newLocale}`, error);
    }
};

// 页面加载时从 localStorage 获取用户选择的语言
onMounted(() => {
    const savedLocale = localStorage.getItem('user-language');
    if (savedLocale && supportedLocales.includes(savedLocale as any)) {
        changeLanguage(savedLocale);
    }
});
</script>

<style scoped>
.language-switcher {
    display: flex;
    gap: 10px;
    padding: 10px;
    margin-bottom: 20px;
}

.language-switcher button {
    padding: 8px 16px;
    background-color: #f0f0f0;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.language-switcher button:hover {
    background-color: #e0e0e0;
}

.language-switcher button.active {
    background-color: #42b983;
    color: white;
    border-color: #42b983;
}
</style>